﻿using System;
using System.Windows.Input;
using System.Windows.Threading;
using System.Diagnostics;

namespace Utils.Wpf
{
    public class ViewModelBase : PropertyChangedNotifier
	{
		#region Attributes

		private bool _isBusy;

		#endregion

		#region Properties

		public bool IsBusy
		{
			get
			{
				return _isBusy;
			}
			protected set
			{
				if (_isBusy != value)
				{
					_isBusy = value;
					this.ChangeCursor();
					this.OnPropertyChanged("IsBusy");
				}
			}
		}

		public Dispatcher Dispatcher { get; set; }

		#endregion

		#region Public Methods

		public ViewModelBase()
		{
			if (System.Threading.Thread.CurrentThread.Name != "Stock Analyst")
			{
				Debug.WriteLine("Invalid thread creating the Dispatcher. Current thread name: " + (string.IsNullOrEmpty(System.Threading.Thread.CurrentThread.Name) ? "<No name>" : System.Threading.Thread.CurrentThread.Name));
			}

			this.Dispatcher = Dispatcher.CurrentDispatcher;
		}

        protected override void OnPropertyChanged(string propertyName)
        {
            if (this.Dispatcher.CheckAccess())
            {
                base.OnPropertyChanged(propertyName);
            }
            else
            {
                this.Dispatcher.BeginInvoke(new Action<string>(this.OnPropertyChanged), new object[] { propertyName });
            }
        }

		#endregion

		#region Private Methods

		private void ChangeCursor()
		{
			if (this.Dispatcher.CheckAccess())
			{
				Mouse.OverrideCursor = this.IsBusy ? Cursors.Wait : null;
			}
			else
			{
				this.Dispatcher.BeginInvoke(new Action(this.ChangeCursor));
			}
		}

		#endregion
	}
}
